# coding= UTF-8

import sys
import json

from tornado.gen import coroutine, Return
from tornado.log import access_log as logger

from core.scanner import ControllerManager
from core.ViewMaker import JsonView
from core.error import ControllerError
from services.conference import api
from services.conference.const import CONFERENCE_MANAGER_PERM
from services.conference.perm_valid import manager_perm_valid

from pojo.json.JsonMsg import MsgMaker
from datetime import datetime
from utils.jwter import JwtGenerator,DEFAULT_EXPIRE_TIME


def transform(data):
    date_str = data.get("date")
    time_str = data.get("time")
    if date_str is None or time_str is None:
        date_obj = None
    else:
        datetime_str = date_str+' '+time_str
        formatter = "%Y-%m-%d %H:%M"
        date_obj=datetime.strptime(datetime_str,formatter)
    return {
        "short_summary":data.get("conference_intro"),
        "meeting_name":data.get("conference_name"),
        "meeting_address":data.get("conference_location"),
        "region":data.get("region"),
        "meeting_time":date_obj,
        "cover":data.get("cover"),
        "long_summary":data.get("long_summary")
    }
@ControllerManager.register(r'/api/conference/submit', ('post'),filters=("jwt"))
@coroutine
def submit_conference(request):
    """
      _step_keys=(('short_summary','meeting_name','meeting_address','meeting_time',"region"),
                ('cover','long_summary'))
    :param request:
    :return:
    """
    req_body = json.loads(request.get_body())
    conference_id = req_body.get('meeting')
    creat_identity_id = req_body.get('publisher')
    step = req_body.get('step')
    conference_data  = req_body.get('data')
    if not creat_identity_id or not conference_data or not step:
        raise ControllerError('error_input')
    return_code = api.submit_conference(request.get_session(),step,conference_id,creat_identity_id,transform(conference_data),request.get_user())
    if return_code is False:
        msg_obj = MsgMaker.badMsg()
    else:
        msg_obj = MsgMaker.goodMsg(data={"conference_id":return_code})
    raise Return(JsonView(msg_obj))  # 返回

@ControllerManager.register(r'/api/conference/remove', ('post'),filters=("jwt"))
@coroutine
def remove_conference(request):
    req_body = json.loads(request.get_body())
    conference_id = req_body.get('meeting')
    creat_identity_id = req_body.get('publisher')
    if not creat_identity_id or not conference_id:
        raise ControllerError('error_input')
    return_code = api.remove_conference(request.get_session(),conference_id,creat_identity_id)
    if not return_code:
        msg_obj = MsgMaker.badMsg()
    else:
        msg_obj = MsgMaker.goodMsg()
    raise Return(JsonView(msg_obj))  # 返回


@ControllerManager.register(r'/api/conference/detail/add', ('post'),filters=("jwt"))
@coroutine
def add_conference_detail(request):
    req_body = json.loads(request.get_body())
    conference_id = req_body.get('meeting')
    creat_identity_id = req_body.get("publisher")
    process_time = req_body.get('time')
    process_content = req_body.get('content')
    session = request.get_session()
    if not conference_id or not process_time or not process_content or not creat_identity_id:
        raise ControllerError('error_input')
    code = api.add_process(session,creat_identity_id,conference_id,process_time,process_content)
    if code:
        msg_obj = MsgMaker.goodMsg()
    else:
        msg_obj = MsgMaker.badMsg()
    raise Return(JsonView(msg_obj))  # 返回


@ControllerManager.register(r'/api/conference/detail/remove', ('post'),filters=('jwt'))
@coroutine
def remove_conference_detail(request):
    req_body = json.loads(request.get_body())
    conference_id = req_body.get('meeting')
    creat_identity_id = req_body.get("publisher")
    process_id = req_body.get("process_id")
    session = request.get_session()
    if not conference_id or not creat_identity_id or not process_id:
        raise ControllerError('error_input')
    api.delete_process(session,creat_identity_id,conference_id,process_id)
    msg_obj = MsgMaker.goodMsg()
    raise Return(JsonView(msg_obj))  # 返回


@ControllerManager.register(r'/api/conference/detail/update', ('post'),filters=("jwt"))
@coroutine
def update_conference_detail(request):
    req_body = json.loads(request.get_body())
    conference_id = req_body.get('meeting')
    process_time = req_body.get('time')
    process_content = req_body.get('content')
    session = request.get_session()
    process_id = req_body.get("process_id")
    creat_identity_id = req_body.get("publisher")
    if not conference_id or not process_time or not process_content or not creat_identity_id or not process_id:
        raise ControllerError('error_input')
    api.update_process(session,creat_identity_id,conference_id,process_id,process_time,process_content)
    msg_obj = MsgMaker.goodMsg()
    raise Return(JsonView(msg_obj))  # 返回


@ControllerManager.register(r'/api/conference/my-create-conference',('get'),filters=('jwt'))
@coroutine
def get_my_create_conference(request):
    user_id = request.get_user()
    data =  api.get_conference_by_creator(int(user_id))
    msg_obj = MsgMaker.goodMsg()
    msg_obj.pushData('conference',data)
    raise Return(JsonView(msg_obj))


@ControllerManager.register(r'/api/conference/my-script-conference',('get'),filters=('jwt'))
@coroutine
def get_script_conference(request):
    user_id = request.get_user()
    data =  api.get_script_conference_by_creator(int(user_id))
    msg_obj = MsgMaker.goodMsg()
    msg_obj.pushData('conference',data)
    raise Return(JsonView(msg_obj))

@ControllerManager.register(r'/api/conference/my-attend-conference',('get'),filters=('jwt'))
@coroutine
def get_my_attend_conference(request):
    user_id = request.get_user()
    data = api.get_my_attend_conference(user_id)
    msg_obj = MsgMaker.goodMsg()
    msg_obj.pushData('attend_list',data)
    raise Return(JsonView(msg_obj))


@ControllerManager.register(r'/api/conference/conference-digest',('get'),filters=('jwt'))
@coroutine
def get_conference_digest(request):
    page = request.get_argument('page')
    if page is None:
        page=0
    else:
        try:
            page=int(page)
        except:
            page=0
    data =  api.get_conference_digest(page)
    msg_obj = MsgMaker.goodMsg()
    msg_obj.pushData('conference',data)
    raise Return(JsonView(msg_obj))


@ControllerManager.register(r'/api/conference/conference-detail',('get'),filters=('jwt'))
@coroutine
def get_conference_detail(request):
    conference_id = request.get_argument('meeting_id')
    if conference_id is None:
        raise ControllerError("error_input",can_out_put=True)
    data =  api.get_conference_detail(conference_id)
    msg_obj = MsgMaker.goodMsg()
    msg_obj.pushData('conference',data)
    raise Return(JsonView(msg_obj))


@ControllerManager.register(r'/api/conference/conference-process',('get'),filters=('jwt'))
@coroutine
def get_conference_process(request):
    conference_id = request.get_argument('meeting_id')
    if conference_id is None:
        raise ControllerError("error_input",can_out_put=True)
    data =  api.get_conference_process(conference_id)
    msg_obj = MsgMaker.goodMsg()
    msg_obj.pushData('process',data)
    raise Return(JsonView(msg_obj))


@ControllerManager.register(r'/api/conference/invitation-register',('post'),filters=('jwt'))
@coroutine
def invitation_register(request):
    invitation_code = request.get_argument('invitation_code')
    user_id = request.get_user()
    if invitation_code is None:
        raise ControllerError("error_input",can_out_put=True)
    code = api.register_invation_code(user_id,invitation_code)
    if code is True:
        msg_obj = MsgMaker.goodMsg()
    else:
        msg_obj = MsgMaker.badMsg()
    raise Return(JsonView(msg_obj))


@ControllerManager.register(r'/api/conference/have-add-perm',('get'),filters=('jwt'))
@coroutine
def get_conference_add_perm(request):
    user_id = request.get_user()
    res = api.have_add_conference_auth(user_id)
    if res:
        session={CONFERENCE_MANAGER_PERM:[each["id"] for each in res]}
        old_session = request.get_session()
        session.update(old_session)
        new_token = JwtGenerator(user_id, DEFAULT_EXPIRE_TIME, session).get()
        msg_obj = MsgMaker.goodMsg(data={"list":res,'token':new_token})
    else:
        msg_obj = MsgMaker.badMsg()
    raise Return(JsonView(msg_obj))


@ControllerManager.register(r'/api/conference/apply-for-conference',('post'),filters=('jwt'))
@coroutine
def get_conference_add_perm(request):
    user_id = request.get_user()
    req_body = json.loads(request.get_body())
    conference_id = req_body.get('meeting')
    conference_data = req_body.get('data')
    user_type = req_body.get("user_type")
    if not conference_id or not conference_data or not user_type:
        raise ControllerError("error input",can_out_put=True)
    api.apply_for_conference(user_id,conference_id,conference_data,user_type)
    msg_obj = MsgMaker.goodMsg()
    raise Return(JsonView(msg_obj))


@ControllerManager.register(r'/api/conference/submit-for-check',('post'),filters=('jwt'))
@coroutine
def get_conference_add_perm(request):
    user_id = request.get_user()
    req_body = json.loads(request.get_body())
    conference_id = req_body.get('meeting')
    creat_identity_id=req_body.get("publisher")
    session=request.get_session()
    if not conference_id or not creat_identity_id:
        raise ControllerError("error input",can_out_put=True)
    code = api.submit_for_check(session,user_id,creat_identity_id,conference_id)
    if code:
        msg_obj = MsgMaker.goodMsg()
    else:
        msg_obj = MsgMaker.badMsg()
    raise Return(JsonView(msg_obj))


@ControllerManager.register(r'/api/conference/description',('get'))
@coroutine
def get_conference_add_perm(request):
    desc_data={
        "valid_code":"验证码说明"
    }
    msg_obj=MsgMaker.goodMsg(data={
        "description":desc_data
    })
    raise Return(JsonView(msg_obj))


@ControllerManager.register(r'/api/conference/sign-up',('post'),filters=("jwt"))
@coroutine
def sign_up_conference(request):
    user_id = request.get_user()
    req_body = json.loads(request.get_body())
    conference_id = req_body.get('meeting')
    if not conference_id:
        raise ControllerError("error input",can_out_put=True)

    code = api.sign_up_for_conference(user_id,conference_id)
    if code:
        msg_obj=MsgMaker.goodMsg()
    else:
        msg_obj=MsgMaker.badMsg()
    raise Return(JsonView(msg_obj))


@ControllerManager.register(r'/api/conference/my-attend-status',('get'),filters=("jwt"))
@coroutine
def my_attend_status(request):
    user_id = request.get_user()
    conference_id = request.get_argument('meeting')
    if not conference_id:
        raise ControllerError("error input",can_out_put=True)

    data = api.my_attend_status(user_id,conference_id)
    if data:
        msg_obj=MsgMaker.goodMsg(data={'attend':data})
    else:
        msg_obj=MsgMaker.badMsg()
    raise Return(JsonView(msg_obj))




